package com.cssy.xxkj.logic.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.attach.dao.AttachFileUploadDAO;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicSalesDAO;
import com.cssy.xxkj.logic.dao.LogicSalesItemDAO;
import com.cssy.xxkj.logic.dao.SystemLogDAO;
import com.cssy.xxkj.logic.entity.LogicSalesDO;
import com.cssy.xxkj.logic.entity.LogicSalesItemDO;
import com.cssy.xxkj.logic.entity.SystemLogDO;
import com.cssy.xxkj.logic.entity.vo.LogicSalesBackVO;
import com.cssy.xxkj.logic.service.ILogicProductionDispatchService;
import com.cssy.xxkj.logic.service.ILogicProductionDispatchingService;
import com.cssy.xxkj.logic.service.ILogicProductionPlanService;
import com.cssy.xxkj.logic.service.ILogicSalesService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 销售订单业务方法
 * @modify hf
 *
 */
@Service("logicSalesService")
public class LogicSalesServiceImpl implements ILogicSalesService {
	private static final Logger logger = Logger.getLogger(LogicSalesServiceImpl.class);
	@Resource(name = "logicSalesDAO")
	private LogicSalesDAO logicSalesDAO;

	@Resource(name = "logicSalesItemDAO")
	private LogicSalesItemDAO  logicSalesItemDAO;

	@Resource(name = "systemLogDAO")
	private SystemLogDAO systemLogDAO;

	@Resource(name = "attachFileUploadDAO")
	private AttachFileUploadDAO attachFileUploadDAO;

	//生产派工service
	@Resource(name = "logicProductionDispatchingService")
	ILogicProductionDispatchingService logicProductionDispatchingService;
	//生产调度service
	@Resource(name = "logicProductionDispatchService")
	ILogicProductionDispatchService logicProductionDispatchService;
	//生产调度service
	@Resource(name = "logicProductionPlanService")
	ILogicProductionPlanService logicProductionPlanService;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;

	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicSalesDO>  list=logicSalesDAO.find(scs);
		rs.setRecordCount(logicSalesDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public SearchResult findBackListByExample(SearchConditions scs)
			throws SyBaseException{
		SearchResult rs = new SearchResult();
		List<LogicSalesBackVO> list = logicSalesDAO.findBackSale(scs);
		rs.setRecordCount(logicSalesDAO.countBackSale(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicSalesDAO.deleteLogicSalesDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicSalesDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicSalesDAO.updateLogicSalesDO(t);
	}

	@Override
	public LogicSalesDO save(LogicSalesDO sodo, User user) throws SyBaseException {
		sodo.setBizCreatorName(user.getName());
		sodo.setBizCreatorDate(new Date());
		sodo.setBizVersion(1);
		logicSalesDAO.insertLogicSalesDO(sodo);
		return sodo;
	}

	@Override
	public LogicSalesDO findListById(String id) throws SyBaseException {
		return logicSalesDAO.findLogicSalesDOByPrimaryKey(id);
	}

	//驳回销售订单
	@Override
	public void backSale(String backId, String zdStepStr, HttpServletRequest request)throws SyBaseException{
		try{
			LogicSalesDO entitySale = logicSalesDAO.findLogicSalesDOByPrimaryKey(backId);
			if(entitySale==null){
				throw new SyBaseException("没有查询到该销售订单，请确认后再提交！");
			}
			if("3".equals(zdStepStr)){
				//该销售订单已调度完成，未派工
				//删除派工记录
				logicProductionDispatchingService.deleteBizRemovedBySaleId(backId);
				//删除调度单记录
				logicProductionDispatchService.deleteBizRemovedBySaleId(backId);
				//删除计划单
				logicProductionPlanService.deleteBizRemovedBySaleId(backId);
				//更改销售订单的状态
				entitySale.setZd024Billstatus(BillStatusUtil.SES_STATUS_SIX);
				entitySale.setBizModifyName(SessionUtil.getUser(request).getName());
				entitySale.setBizModifyDate(new Date());
				entitySale.setBizVersionMark(entitySale.getBizVersion());
				entitySale.setBizVersion(entitySale.getBizVersion()+1);
				logicSalesDAO.updateLogicSalesDO(entitySale);

			}else if("2".equals(zdStepStr)){
				//该销售订单存在调度记录且调度记录没有完成
				//删除调度单记录
				logicProductionDispatchService.deleteBizRemovedBySaleId(backId);
				//删除计划单
				logicProductionPlanService.deleteBizRemovedBySaleId(backId);
				//更改销售订单的状态
				entitySale.setZd024Billstatus(BillStatusUtil.SES_STATUS_SIX);
				entitySale.setBizModifyName(SessionUtil.getUser(request).getName());
				entitySale.setBizModifyDate(new Date());
				entitySale.setBizVersionMark(entitySale.getBizVersion());
				entitySale.setBizVersion(entitySale.getBizVersion()+1);
				logicSalesDAO.updateLogicSalesDO(entitySale);
			}else if("1".equals(zdStepStr)){
				//存在计划单据
				//删除计划单
				logicProductionPlanService.deleteBizRemovedBySaleId(backId);
				//更改销售订单的状态
				entitySale.setZd024Billstatus(BillStatusUtil.SES_STATUS_SIX);
				entitySale.setBizModifyName(SessionUtil.getUser(request).getName());
				entitySale.setBizModifyDate(new Date());
				entitySale.setBizVersionMark(entitySale.getBizVersion());
				entitySale.setBizVersion(entitySale.getBizVersion()+1);
				logicSalesDAO.updateLogicSalesDO(entitySale);
			}else if("0".equals(zdStepStr)){
				//生产审核完成
				//更改销售订单的状态
				entitySale.setZd024Billstatus(BillStatusUtil.SES_STATUS_SIX);
				entitySale.setBizModifyName(SessionUtil.getUser(request).getName());
				entitySale.setBizModifyDate(new Date());
				entitySale.setBizVersionMark(entitySale.getBizVersion());
				entitySale.setBizVersion(entitySale.getBizVersion()+1);
				logicSalesDAO.updateLogicSalesDO(entitySale);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException("操作销售订单失败!");
		}
	}

	@Override
	public void salesSave(HttpServletRequest request, LogicSalesDO curAP)
			throws SyBaseException {
		try {
			String itemdata = request.getParameter("itemdata");//物品数据
			String deldata = request.getParameter("itemdelete");//物品数据
			String submitFlag =request.getParameter("submitFlag");
			curAP.setZd024Billstatus(submitFlag);//单据状态
			List<LogicSalesItemDO> salesItemlist = JSONArray.parseArray(itemdata,LogicSalesItemDO.class);
			/*
			 * 获取操作
			 * 0为保存(草稿状态)
			 * 1为提交(待审核状态)
			 * 2财务审核(提交二级审核)
			 * 3生产审核(提交三级审核)
			 * 4生产中
			 * 5生产完成
			 */

			User user = SessionUtil.getUser(request);
			Date curDate = new Date();
			curAP.setZd025WareStatus(0);
			if(BillStatusUtil.SES_STATUS_SIX.equals(submitFlag)||BillStatusUtil.SES_STATUS_ONE.equals(submitFlag)||BillStatusUtil.SES_STATUS_TWO.equals(submitFlag)){
				if (StringUtils.isBlank(curAP.getId())) {
					String id = IDCodeTypeUtil.getId();
					curAP.setId(id);
					curAP.setZd001FormCode(syCodeService.getCode(BillTypeConstant.SALES,BillTypeConstant.SALES,SyCode.DATE_YYMM,5));

					//日期转换处理
					String bizCreatorDate = request.getParameter("bizCreatorDate");//开单日期没有填写的情况下默认当前时间
					if(StringUtils.isNotBlank(bizCreatorDate)){
						curAP.setBizCreatorDate(DateUtils.stringToDate(bizCreatorDate));
					}else{
						curAP.setBizCreatorDate(curDate);
					}
					String zd017DeliveryDate = request.getParameter("zd017DeliveryDate");
					if(StringUtils.isNotBlank(zd017DeliveryDate)){
						curAP.setZd017DeliveryDate(DateUtils.stringToDate(zd017DeliveryDate));
					}
					this.save(curAP,user);
					curAP.setId(id);
					for (LogicSalesItemDO soItemDO : salesItemlist) {
						soItemDO.setZd001SalesId(id);
						soItemDO.setId(IDCodeTypeUtil.getId());
						logicSalesItemDAO.insertLogicSalesItemDO(soItemDO);
					}
					logger.info("新增销售订单成功");
				} else {
					//日期转换处理
					String bizCreatorDate = request.getParameter("bizCreatorDate");//开单日期没有填写的情况下默认当前时间
					if(StringUtils.isNotBlank(bizCreatorDate)){
						curAP.setBizCreatorDate(DateUtils.stringToDate(bizCreatorDate));
					}else{
						curAP.setBizCreatorDate(curDate);
					}
					String zd017DeliveryDate = request.getParameter("zd017DeliveryDate");
					if(StringUtils.isNotBlank(zd017DeliveryDate)){
						curAP.setZd017DeliveryDate(DateUtils.stringToDate(zd017DeliveryDate));
					}
					int rs=this.update(curAP, user);
					if(0==rs){
						throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
					}
					if(deldata!=null&&!"".equals(deldata)){
						List<LogicSalesItemDO> salesItemdellist = JSONArray.parseArray(deldata,LogicSalesItemDO.class);
						if(salesItemdellist!=null&&!salesItemdellist.isEmpty()&&salesItemdellist.size()>0){
							for(int i=0;i<salesItemdellist.size();i++){
								if(salesItemdellist.get(i).getId()!=null&&!"".equals(salesItemdellist.get(i).getId())){
									logicSalesItemDAO.deleteLogicSalesItemDOByPrimaryKey(salesItemdellist.get(i).getId());
								}
							}
						}
					}
					if(salesItemlist!=null&&!salesItemlist.isEmpty()&&salesItemlist.size()>0){
						for(int i=0;i<salesItemlist.size();i++){
							if(salesItemlist.get(i).getId()!=null&&!"".equals(salesItemlist.get(i).getId())){
								logicSalesItemDAO.updateLogicSalesItemDO(salesItemlist.get(i));
							}else{
								salesItemlist.get(i).setZd001SalesId(curAP.getId());
								salesItemlist.get(i).setId(IDCodeTypeUtil.getId());
								logicSalesItemDAO.insertLogicSalesItemDO(salesItemlist.get(i));
							}
						}
					}
					logger.info("修改销售订单成功");
				}
			}
			if(BillStatusUtil.SES_STATUS_THREE.equals(submitFlag)){
				this.modifyState(request,curAP);
				logger.info("财务审核成功");
			}
			if(BillStatusUtil.SES_STATUS_FOUR.equals(submitFlag)){
				this.modifyState(request,curAP);
				logger.info("生产审核成功");
			}
			//保存附件
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("filePath");
			if(file.isEmpty() || file.getSize()==0){
				return ;
			}else{
				attachFileUploadDAO.save(request, file, curAP.getId(), "com.cssy.xxkj.logic.entity.LogicSalesDO", "ATTACH_LG_SA");
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("操作销售订单失败！");
			throw new SyBaseException("操作销售订单失败!");
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicSalesDAO.deleteBizRemoved(id);
	}

	@Override
	public void modifyState(HttpServletRequest request,LogicSalesDO logicSalesDO) throws SyBaseException {
		SystemLogDO log =new SystemLogDO();
		LogicSalesDO logicDO = new LogicSalesDO();
		try{
			logicDO.setId(logicSalesDO.getId());
			logicDO.setZd024Billstatus(logicSalesDO.getZd024Billstatus());
			logicDO.setBizVersion(logicSalesDO.getBizVersion());
			log.setId(IDCodeTypeUtil.getId());
			log.setZd001UserName(SessionUtil.getUser(request).getName());
			log.setZd002ModelName("销售订单");
			log.setZd003ModelCode(logicSalesDO.getZd001FormCode());
			int rs=this.update(logicDO, SessionUtil.getUser(request));
			if(0==rs){
				throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
			}
			if(BillStatusUtil.SES_STATUS_THREE.equals(logicSalesDO.getZd024Billstatus())){
				log.setZd004Action("财务审核");
				log.setZd005ActionTime(new Date());
			}
			if(BillStatusUtil.SES_STATUS_FOUR.equals(logicSalesDO.getZd024Billstatus())){
				log.setZd004Action("生产审核");
				log.setZd005ActionTime(new Date());
			}
			log.setZd006ActionState(0);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			log.setZd006ActionState(1);
			logger.error("操作销售订单审核失败！");
			throw new SyBaseException("操作销售订单审核失败!");
		}
		systemLogDAO.insertSystemLogDO(log);
	}

	@Override
	public List<LogicSalesItemDO> findSalesItemList(String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		if(scs.getOrderBy()==null){
			scs.setOrderBy("(zd043Order + 0)");
		}
		scs.addCondition("zd001SalesId", id, SearchCondition.OP_EQUAL);
		List<LogicSalesItemDO>  list=logicSalesItemDAO.find(scs);
		return list;
	}

	@Override
	public List<LogicSalesItemDO> findSalesItemListByMap(Map<String, Object> paramMap) throws SyBaseException {
		return logicSalesItemDAO.findListByMap(paramMap);
	}


	@Override
	public boolean checkPiCode(String code,String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		scs.addCondition("zd002PiCode", code, SearchCondition.OP_EQUAL);
		scs.addCondition("id", id, SearchCondition.OP_NOTEQUAL);
		List<LogicSalesDO>  list=logicSalesDAO.find(scs);
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			return false;
		}else{
			return true;
		}
	}

}
